(function (factory) {
    var nameSpace = 'field_8337845202406142046';
    if (!window[nameSpace]) {
        var Builder = factory();
        window[nameSpace] = {
            instance: {}
        };
        window[nameSpace].init = function (options) {
            window[nameSpace].instance[options.privateId] = new Builder(options);
        };
        window[nameSpace].isNotNull = function (obj) {
            return true;
        };
    }
})(function () {
    /**
     * 构造函数
     * @param options
     * @constructor
     */
    function App(options) {
        var self = this;
        //初始化参数
        self.initParams(options);
        //初始化dom
        self.initDom();
        //事件
        self.events();
    }

    App.prototype = {
        initParams: function (options) {
            var self = this;
            self.adaptation = options.adaptation;
            self.privateId = options.privateId;
            self.messageObj = options.getData;
            self.preUrl = options.url_prefix;
        },
        initDom: function () {
            var self = this;
            dynamicLoading.css(self.preUrl + 'css/sealBtn.css');
            self.appendChildDom();
        },
        events: function () {
            var self = this;
            // 监听是否数据刷新
            self.adaptation.ObserverEvent.listen('Event' + self.privateId, function () {
                self.messageObj = self.adaptation.childrenGetData(self.privateId);
                self.appendChildDom();
            });
        },
        appendChildDom: function () {
            var self = this;
            var domStructure = '<section class="customButton_box_content">' +
                '<div class="customButton_class_box ' + self.privateId + '" title="' + self.messageObj.display.escapeHTML() + '">' + self.messageObj.display.escapeHTML() + '</div>' +
                '</section>';
            document.querySelector('#' + self.privateId).innerHTML = domStructure;
            var jumpFun = function () {
                // 事件执行
                csdk.util.openMask()
                var subData = csdk.core.getFormData()
                console.log(subData)
                //组装参数信息
                var params = {'dataId': subData.metadata.content.contentDataId};
                //调用后端接口
                $.ajax({
                    url: "/seeyon/rest/jssdk/downLoadSealPdf",
                    data: JSON.stringify(params),
                    type: "POST",
                    contentType: "application/json;charset=UTF-8",
                    error: function (data) {
//                alert(data);
                    },
                    success: function (data) {
                        console.log(data)
                        if (data[0].status == 200) {
//                               window.open(data.filesUrl);
                             for (let i = 0; i < data.length; i++) {
                                  console.log(data[i]); // 从0打印到9
                                  //下载文件 并指定文件名
                                  const xhr = new XMLHttpRequest();
                                  xhr.open('GET', data[i].filesUrl, true);
                                  xhr.responseType = 'blob';
                                  xhr.onload = function() {
                                      if (this.status === 200) {
                                          const blob = this.response;
                                          const url = window.URL.createObjectURL(blob);
                                          const link = document.createElement('a');
                                          link.href = url;
                                          link.setAttribute('download', data[i].fileName); // 设置下载的文件名
                                          link.style.display = 'none';
                                          document.body.appendChild(link);
                                          link.click();
                                          document.body.removeChild(link); // 清理创建的<a>标签
                                          window.URL.revokeObjectURL(url); // 释放创建的URL对象
                                      }
                                  };

                                  xhr.send();
                            }
                        }
                        csdk.util.closeMask()
                        csdk.util.alert(data[0].msg)
                    }
                });
            };
            document.querySelector('.' + self.privateId).removeEventListener('click', jumpFun);
            document.querySelector('.' + self.privateId).addEventListener('click', jumpFun);
            //渲染隐藏权限
            if (self.messageObj.auth === 'hide') {
                document.querySelector('#' + self.privateId).innerHTML = '<div class="cap4-text__browse" style="line-height: 1.8; color: rgb(0, 0, 0) !important;">***</div>';
            }
        },
        dealCdtMapping: function (opt) {
            $.ajax({
                url: '/seeyon/rest/cap4/formquerybtn/dealCdtMapping?formId=' + opt.formId + '&fieldName=' + opt.fieldName + '&formDataId=' + opt.formDataId + '&formSubDataId=' + opt.formSubDataId + '&designId=' + opt.designId,
                success: function (data) {
                    if (opt.callback && typeof opt.callback === 'function')
                        opt.callback.apply();
                },
                error: function (e) {
                    if (e.message) {
                        top.$.error(e.message);
                    } else {
                        top.$.error('处理筛查条件出错...');
                    }
                }
            });
        }
    };

    var dynamicLoading = {
        css: function (path) {
            if (!path || path.length === 0) {
                throw new Error('argument "path" is required !');
            }
            var head = document.getElementsByTagName('head')[0];
            var link = document.createElement('link');
            link.href = path;
            link.rel = 'stylesheet';
            link.type = 'text/css';
            head.appendChild(link);
        },
        js: function (path) {
            if (!path || path.length === 0) {
                throw new Error('argument "path" is required !');
            }
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            script.src = path;
            script.type = 'text/javascript';
            head.appendChild(script);
        }
    }

    return App;
});